
#include "cmd_mng_session.hpp"

cmd_mng_session::cmd_mng_session(io_service& ioserv, const tcp_endpoint& rep):
    _ioserv(ioserv), _socket(ioserv), _rep(rep)
{
    PDBG("create cmd_mng_session\n");
}

cmd_mng_session::~cmd_mng_session() 
{
    disconnect();
    PDBG("delete cmd_mng_session\n");
}


tcp_socket& cmd_mng_session::socket()
{
    return _socket;
}

bool cmd_mng_session::connect()
{
    boost::system::error_code error = boost::asio::error::host_not_found;

    if (_socket.is_open()) {
        PDBG("socket is opened!!\n");
        return true;
    }

    _socket.close();
    _socket.connect(_rep, error);
    if (error) {
        disconnect();
        PDBG("exception: %s\n", error.message().c_str());    
        return false;
    }
    PDBG("connected peer!\n");
    return true;
};

bool cmd_mng_session::send_msg(vty_ipc_message_t& msg)
{
    msg.encode_header();
    boost::system::error_code error;
    boost::asio::write(socket(), 
            boost::asio::buffer(msg.data(), msg.length()),
            boost::asio::transfer_all(), error);

    if (error) {
        disconnect();
        PDBG("exception: %s\n", error.message().c_str());    
        return false;
    }
    return true;
}

bool cmd_mng_session::recv_msg(vty_ipc_message_t& msg)
{
    boost::system::error_code error;
    size_t len = boost::asio::read(socket(),
            boost::asio::buffer(msg.data(), vty_ipc_message_t::header_length),
            boost::asio::transfer_all(), error);
    //PDBG("read size: %d\n", len);

    if (error) {
        disconnect();
    //    throw boost::system::system_error(error);
        return false;
    }

    msg.decode_header();
    //PDBG("body size: %d\n", msg.body_length());
    if (msg.body_length()) {
        len = boost::asio::read(socket(),
                boost::asio::buffer(msg.body(), msg.body_length()),
                boost::asio::transfer_all(), error);
        //PDBG("recevied body size: %d\n", len);
    }
    return true;
}
